$(function() {

	$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
		options.url = conquest.static.restPath + options.url + '?language=' + conquest.static.language;
	});

	var ViewBase = Backbone.View.extend({
		el: '.content',
		events: {
			'click a': 'linkClick'
		},
		linkClick: function(e) {
			var root = conquest.static.root;
			var href = $(e.currentTarget).attr('href');
			if (href.indexOf(root) == 0) {
				e.preventDefault();			
				conquest.router.navigate(href.replace(conquest.static.root, ''), {trigger: true});
			}
		},
		renderMessages: function(options) {
			if (this.messages) {
				var $template = $(Handlebars.templates['global-messages.hbs']({
					messages: this.messages
				}));
				delete this.messages;
				this.$el.prepend($template);
				setTimeout(function() {
					$template.fadeOut("slow");
				}, 2000);
			}
		}
	});

	var CardView = ViewBase.extend({
		render: function(setNumber, cardNumber) {
			var card = conquest.dict.findCardByNumber(setNumber, cardNumber);
			var template = Handlebars.templates['card-view.hbs']({
				card: card
			});
			this.$el.html(template);
			conquest.router.navigate(conquest.util.toCardRelativeUrl(card));		
		}
	});	

	var CardSearchView = ViewBase.extend({
		filterProperties: ['set'],
		render: function(queryString) {
			// var queryItems = queryString.split('&');
			// var queryPairs = [];
			// _.each(queryItems, function(queryItem))
			// 	var queryPair = queryItem.split('=');
			// 	queryPairs.push([decodeURIComponent(queryPair[0]), decodeURIComponent(queryPair[0])]);
			// }
			

			// var card = conquest.dict.findCardByNumber(setNumber, cardNumber);
			// var template = Handlebars.templates['card-view.hbs']({
			// 	card: card
			// });
			// this.$el.html(template);
			// conquest.router.navigate(conquest.util.toCardRelativeUrl(card));		
		}
	});	

	var Router = Backbone.Router.extend({
		routes: {
			':setNumber/:cardNumber': 'viewCard',
			'search?query=:query' : 'searchCards'
		}
	});
	
	conquest.router = new Router();
	conquest.router.on('route:viewCard', function(setNumber, cardNumber) {
		var cardView = new CardView();
		cardView.render(parseInt(setNumber), parseInt(cardNumber));
	}).on('route:searchCards', function(queryString) {
		var cardSearchView = new CardSearchView();
		cardSearchView.render(queryString);
	});

	conquest.static.root = '/' + conquest.static.language + '/card/';

	Backbone.history.start({
		pushState: true,
		root: conquest.static.root
	});
});